Operators


We are now going to explore Operators. They are single or bi character symbols represent a specific type of operation, say addition, multiplication or comparision.

Python provides many types of operators. We will explore them based on their functionality namely.

  • Assignment Operators
  • Arithmetic Operators
  • Relational Operators
  • Logical/Boolean Operators
  • Bitwise Operators

Arithmetic Operators

Python supports all most common maths operations as shown in the below table

Syntax Math Operation Name
a + b a + b addition
a - b a - b subtraction
a * b a * b multiplication
a / b a \div b division (see note below)
a // b a//b floor division (e.g. 5//2=2)
a % b a % b modulo
-a -a negation
abs(a) | a | absolute value
a**b a**b exponent
math.sqrt(a) sqrt a square root

Note
In order to use math.sqrt() function, you must explicitly load the math module by adding import math at the top of your file, where all the other modules import's are defined.

We will explore the below operators with various primary data types

Numeric Vs Numeric

Following mathemetical operations are supported in python between numeric data


In [17]:
a = 10
b = 22
print("a =", a, ", b =", b)
print("~~~~~~~~~~~~~~~~~")
print("a + b:\t", a + b)
print("a - b:\t", a - b)
print("a * b:\t", a * b)
print("a / b:\t", a / b)
print("a//b:\t", a//b)
print("a % b:\t", a % b)
print("-a:\t", -a)
print("a < b:\t", a < b)
print("a > b:\t", a > b)
print("a <= b:\t", a <= b)
print("a >= b:\t", a >= b)
print("abs(a):\t", abs(a))
import math
print("sqrt(a):", math.sqrt(a))


a = 10 , b = 22
~~~~~~~~~~~~~~~~~
a + b:	 32
a - b:	 -12
a * b:	 220
a / b:	 0.45454545454545453
a//b:	 0
a % b:	 10
-a:	 -10
a < b:	 True
a > b:	 False
a <= b:	 True
a >= b:	 False
abs(a):	 10
sqrt(a): 3.1622776601683795

Numeric Vs String


In [26]:
a = "10"
b = 22
print("a =", a, ", b =", b)
print("~~~~~~~~~~~~~~~~~")
# print("a + b:\t", a + b)
# print("a - b:\t", a - b)
print("a * b:\t", a * b)
# print("a / b:\t", a / b)
# print("a//b:\t", a//b)
# print("a % b:\t", a % b)
# print("-a:\t", -a)
# print("a < b:\t", a < b)
# print("a > b:\t", a > b)
# print("a <= b:\t", a <= b)
# print("a >= b:\t", a >= b)
# print("abs(a):\t", abs(a))
# import math
# print("sqrt(a):", math.sqrt(a))


a = 10 , b = 22
~~~~~~~~~~~~~~~~~
a * b:	 10101010101010101010101010101010101010101010

As shown above only "*" multiplication is possible between string & real numeric value

Complex Vs String


In [31]:
a = "10"
b = 22 + 4j
print("a =", a, ", b =", b)
print("~~~~~~~~~~~~~~~~~")
try:
    print("a * b:\t", a * b)
except Exception as e:
    print(e)


a = 10 , b = (22+4j)
~~~~~~~~~~~~~~~~~
can't multiply sequence by non-int of type 'complex'

Complex Vs Numeric


In [9]:
a = 10 + 4j
b = 10
print("a =", a, ", b =", b)
print("~~~~~~~~~~~~~~~~~")
print("a + b:\t", a + b)
print("a - b:\t", a - b)
print("a * b:\t", a * b)
print("a / b:\t", a / b)
# print("a//b:\t", a//b)
# print("a % b:\t", a % b)
print("-a:\t", -a)
# print("a < b:\t", a < b)
# print("a > b:\t", a > b)
# print("a <= b:\t", a <= b)
# print("a >= b:\t", a >= b)
print("abs(a):\t", abs(a))
import math
# print("sqrt(a):", math.sqrt(a))


a = (10+4j) , b = 10
~~~~~~~~~~~~~~~~~
a + b:	 (20+4j)
a - b:	 4j
a * b:	 (100+40j)
a / b:	 (1+0.4j)
-a:	 (-10-4j)
abs(a):	 10.770329614269007

Thus we can see that following operations are not possible with complex data type floor (//), mod (%), compare (<, >, >=, <=).

Assignment Operators

Syntax Math Operation Name
+= a + b addition
-= a - b subtraction
*= a * b multiplication
/= a \div b division (see note below)
//= a//b floor division (e.g. 5//2=2)
%= a % b modulo

Numeric

Int

In [46]:
a = 10
c = 0 
c += a
print("c =", c)
c -= a/2
print("c =", c)
c *= a
print("c =", c)
c /= a
print("c =", c)
c **= a
print("c =", c)
c //= a
print("c =", c)
c %= a
print("c =", c)


c = 10
c = 5.0
c = 50.0
c = 5.0
c = 9765625.0
c = 976562.0
c = 2.0

Real Number


In [44]:
a = 10.20
c = 0 
c += a
print("c =", c)
c -= a/2
print("c =", c)
c *= a
print("c =", c)
c /= a
print("c =", c)
c **= a
print("c =", c)
c //= a
print("c =", c)
c %= a
print("c =", c)


c = 10.2
c = 5.1
c = 52.019999999999996
c = 5.1
c = 16489815.489690851
c = 1616648.0
c = 9.200000000112617

Complex Number


In [50]:
a = 10 + 20j
c = 0 
c += a
print("c =", c)
c -= a/2
print("c =", c)
c *= a
print("c =", c)
c /= a
print("c =", c)
c **= a
print("c =", c)
# c //= a
# print("c =", c)
# c %= a
# print("c =", c)


c = (10+20j)
c = (5+10j)
c = (-150+200j)
c = (5+10j)
c = (-6.966954518433685+2.4303120039373587j)

Boolean Number


In [51]:
a = True
c = 0 
c += a
print("c =", c)
c -= a/2
print("c =", c)
c *= a
print("c =", c)
c /= a
print("c =", c)
c **= a
print("c =", c)
c //= a
print("c =", c)
c %= a
print("c =", c)


c = 1
c = 0.5
c = 0.5
c = 0.5
c = 0.5
c = 0.0
c = 0.0

In [55]:
a = False
c = 0 
c += a
print("c =", c)
c -= a/2
print("c =", c)
c *= a
print("c =", c)
# c /= a
# print("c =", c)
c **= a
print("c =", c)
# c //= a
# print("c =", c)
# c %= a
# print("c =", c)


c = 0
c = 0.0
c = 0.0
c = 1.0

Relational Operators


In [ ]:
There are following relational operators supported by Python language
Syntax Math Operation Name
< a < b Less- than
> a > b Greater- than
<= a <= b Less- than- equal
>= a >= b Greater- than- equal
== a == b Equal to
!= a != b not equal to

Numeric Vs Numeric


In [28]:
a = 10
b = 21.22

print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
print(a == b)
print(a != b)


True
False
True
False
False
True

Numeric Vs String


In [16]:
a = 10
b = "Mayank Shrivastava"

# print(a < b)
# print(a > b)
# print(a <= b)
# print(a >= b)
print(a == b)
print(a != b)


False
True

Numeric Vs Complex


In [13]:
a = 10
b = 10 + 21j

# print(a < b)
# print(a > b)
# print(a <= b)
# print(a >= b)
print(a == b)
print(a != b)


False
True

Complex Vs Complex


In [11]:
a = 10 + 20j
b = 10 + 21j

# print(a < b)
# print(a > b)
# print(a <= b)
# print(a >= b)
print(a == b)
print(a != b)


False
True

Complex Vs String


In [8]:
a = 10 + 20j
b = "Rishi Rai"

# print(a < b)
# print(a > b)
# print(a <= b)
# print(a >= b)
print(a == b)
print(a != b)


False
True

String Vs String


In [19]:
a = "Manish Nandle"
b = "Saurabh Dubey"

print(a < b)
print(a > b)
print(a <= b)
print(a >= b)
print(a == b)
print(a != b)


True
False
True
False
False
True

Logical/Boolean Operators


In [ ]:

Syntax example Operation Name Meaning
and a and b Logical AND returns true if and only if both expressions are true
or a or b Logical OR returns true if and only if even an expressions are true
not not(a and b) Logical NOT returns reverse of the expression
is a is b Logical IS returns true both references are same object else false
in in Logical IN returns true if first is found in second else false

Example:


In [1]:
print (0 and 3) # Shows 0
print (2 and 3 )# Shows 3

print (0 or 3) # Shows 3
print (2 or 3) # Shows 2

print (not 0) # Shows True
print (not 2) # Shows False
print (2 in (2, 3)) # Shows True
print (2 is 3) # Shows False


0
3
3
2
True
False
True
False

In [ ]:

Besides boolean operators, there are the functions all(), which returns true when all of the items in the sequence passed as parameters are true, and any(), which returns true if any item is true.

Bitwise Operators

  • Left Shift (<<)
  • Right Shift (>>)
  • And (&)
  • Or (|)
  • Exclusive Or (^)
  • Inversion (~)

In [ ]:
a = "Sunil Kumar Bhele"

In [36]:
x = 10 #-> 1010 
y = 11 #-> 1011
1011
"""
OR
0 0 | 0 
0 1 | 1
1 0 | 1
1 1 | 1
AND
0 0 | 0
0 1 | 0
1 0 | 0
1 1 | 1
"""

In [25]:
x = 10 #-> 1010 
y = 11 #-> 1011

print("x << 2 = ", x<<2)
print("x =", x)
print("x >> 2 = ", x>>2)
print("x &y  = ", x&y)
print("x | y  = ", x|y)
print("x^y = ", x^y)
print("x =", x)
print("~x = ", ~x)
print("~y = ", ~y)


x << 2 =  40
x = 10
x >> 2 =  2
x &y  =  10
x | y  =  11
x^y =  1
x = 10
~x =  -11
~y =  -12

Order of Operations


Python uses the standard order of operations as taught in Algebra and Geometry classes. That, mathematical expressions are evaluated in the following order (memorized by many as PEMDAS or BODMAS {Brackets, Orders or pOwers, Division, Multiplication, Addition, Subtraction}) .

(Note that operations which share a table row are performed from left to right. That is, a division to the left of a multiplication, with no parentheses between them, is performed before the multiplication simply because it is to the left.)

Name Syntax Description PEMDAS Mnemonic
Parentheses ( ... ) Before operating on anything else, Python must evaluate all parentheticals starting at the innermost level. (This includes functions.) Please
Exponents ** As an exponent is simply short multiplication or division, it should be evaluated before them. Excuse
Multiplication and Division * / // % Again, multiplication is rapid addition and must, therefore, happen first. My Dear
Addition and Subtraction + - They should happen independent to one another and finally operated among eachother Aunt Sally
operators descriptions
(), [], {}, ‘’ tuple, list, dictionnary, string
x.attr, x[], x[i:j], f() attribute, index, slide, function call
+x, -x, ~x unary negation, bitwise invert
** exponent
*, /, % multiplication, division, modulo
+, - addition, substraction
<<, >> bitwise shifts
& bitwise and
^ bitwise xor
bitwise or
<, <=, >=, > comparison operators
==, !=, is, is not, in, comparison operators (continue)
not in comparison operators (continue)
not boolean NOT
and boolean AND
or boolean OR
lambda lamnda expression

Formatting output


round()


In [21]:
print (round(3.14159265, 2))


3.14

During the operations, numbers are converted appropriately (eg. (1.5 + 4j) + 3 gives 4.5 + 4j).

Besides operators, there are also some builtin features to handle numeric types: abs(), which returns the absolute value of the number, oct(), which converts to octal, hex(), which converts for hexadecimal, pow(), which raises a number by another and round(), which returns a real number with the specified rounding.

Review

what is the output of the followings:

  • print(0.1 + 0.11 == 0.12)
    

Ans: False

  • print(0.11 + 0.2 == 0.31)
    

Ans: True

  • print(~1011)
    

Ans: -1012

  • b = 0x1000
    a = 10
    a = b
    print(a, b)
    

Ans: 4096 4096

  • 5 + 2 // 4
    

Ans: 5

  • (5 + 2)%(1 + 4/2)
    

Ans: 1.0

  • 5 + 2%4
    

Ans: 7

  • 5 + 2*4
    

Ans: 13

  • 5 % 2*4 // 2
    

Ans: 2

  • int(5.55 % 2+3/3)
    

Ans: 2

  • round(5.55 % 2+3/3)
    

Ans: 3

  • ~~~~15
    

Ans: 15

  • 2**(3**2)
    

Ans: 512

  • (2**3)**2
    

Ans: 64

  • 2**3**2
    

Ans: 512

  • a = 1
    a, b = a+1, a+1
    print(a)
    print(b)
    

Ans:

2
2
  • i + = 1
    

Ans: SyntaxError: invalid syntax

Reference, Recommendation, Remarks & Thanks